package cn.cjlmonster.demo02;

import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.github.mikephil.charting.animation.Easing;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.ValueFormatter;
import com.google.android.material.tabs.TabLayout;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import cn.cjlmonster.demo02.data.SnapshotData;
import cn.cjlmonster.demo02.entity.Snapshot;
import cn.cjlmonster.demo02.utils.DpUtils;
import cn.cjlmonster.demo02.widget.MyMarkerView;

/**
 * This project is Demo02
 * Created by cjl on 2021/11/21 11:33 上午.
 */

public class ChartDialog extends Dialog {

    public static void show(Context context) {
        ChartDialog dialog = new ChartDialog(context);
        dialog.show();
    }

    private LineChart lineChart;

    private ChartDialog(@NonNull Context context) {
        super(context, R.style.BaseDialog);
        setContentView(R.layout.dialog_chart);
        setCancelable(false);
        getWindow().getAttributes().width = LinearLayout.LayoutParams.MATCH_PARENT;
        getWindow().getAttributes().height = DpUtils.dpToPx(context, 400);
        findViewById(R.id.btn_close).setOnClickListener(v -> dismiss());

        lineChart = findViewById(R.id.lineChart);
        lineChart.setScaleEnabled(false);
        lineChart.setPinchZoom(false);

        initIndicator();
    }

    private Map<SnapshotData.Unit, List<Snapshot>> dataMap;

    private void initIndicator() {
        dataMap = new HashMap<>();
        TabLayout tabLayout = findViewById(R.id.tabLayout);
        String[] titles = {"日", "周", "月"};
        for (String title : titles) {
            tabLayout.addTab(tabLayout.newTab().setText(title));
        }
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                SnapshotData.Unit unit = SnapshotData.Unit.month;
                if (tab.getPosition() == 0) {
                    unit = SnapshotData.Unit.day;
                } else if (tab.getPosition() == 1) {
                    unit = SnapshotData.Unit.week;
                }
                initDataSet(unit);
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
        initDataSet(SnapshotData.Unit.day);
    }

    private void initDataSet(SnapshotData.Unit unit) {

        lineChart.reset();

        List<Snapshot> mSnapshots = dataMap.get(unit);
        if (mSnapshots == null) {
            mSnapshots = SnapshotData.createSnapshots(unit);
            dataMap.put(unit, mSnapshots);
        }

        List<Entry> mEntries = new ArrayList<>();
        for (int i = 0; i < mSnapshots.size(); i++) {
            mEntries.add(new Entry(i, mSnapshots.get(i).getValue()));
        }
        LineDataSet dataSet = new LineDataSet(mEntries, "用电量");
        dataSet.setMode(LineDataSet.Mode.CUBIC_BEZIER);
        dataSet.setDrawCircles(false);
        dataSet.setDrawFilled(true);
        GradientDrawable drawable = new GradientDrawable(
                GradientDrawable.Orientation.TOP_BOTTOM,
                new int[]{
                        Color.parseColor("#FF03A9F4"),
                        Color.parseColor("#10000000")
                }
        );
        dataSet.setColor(Color.parseColor("#FF03A9F4"));
        dataSet.setFillDrawable(drawable);

        XAxis xAxis = lineChart.getXAxis();
        xAxis.setDrawAxisLine(true);
//        xAxis.setDrawLimitLinesBehindData(true);
        xAxis.setDrawLabels(true);
        xAxis.setDrawGridLines(false);
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setAxisMinimum(0f);//设置轴的最小值。这样设置将不会根据提供的数据自动计算。
        xAxis.setGranularityEnabled(true);    //粒度
        xAxis.setGranularity(1f);    //缩放的时候有用，比如放大的时候，我不想把横轴的月份再细分
        xAxis.setValueFormatter(new UnitValueFormatter(unit, mSnapshots));
        xAxis.setTextSize(12f);
        xAxis.setTextColor(Color.WHITE);
        xAxis.setAvoidFirstLastClipping(true);

//        lineChart.setExtraBottomOffset(15f);
        lineChart.setExtraOffsets(15f, 15f, 15f, 15f);

        lineChart.getAxisLeft().setDrawZeroLine(false);
        lineChart.getAxisLeft().setDrawAxisLine(false);
        lineChart.getAxisLeft().setDrawLabels(false);
        lineChart.getAxisRight().setEnabled(false);

        LineData lineData = new LineData(dataSet);
        lineData.setDrawValues(false);

        lineChart.setData(lineData);


        UnitMarkerView markerView = new UnitMarkerView(getContext(), unit, mSnapshots);
        markerView.setChartView(lineChart);
        lineChart.setMarker(markerView);

        lineChart.setDescription(null);

        lineChart.getLegend().setEnabled(false);

        //设置一页最大显示个数为6，超出部分就滑动
        float ratio = (float) mEntries.size() / (float) xAxis.getLabelCount();
        //显示的时候是按照多大的比率缩放显示,1f表示不放大缩小
//        lineChart.zoom(0f, 1, 0, 0);
        lineChart.fitScreen();
        lineChart.zoom(ratio, 1f, 0, 0);
//        lineChart.fitScreen();
//        lineChart.setVisibleXRangeMaximum(10);
//        lineChart.moveViewToX(0);
        //设置从X轴出来的动画时间
        lineChart.animateXY(1500, 1500, Easing.EaseOutSine, Easing.EaseOutSine);

//        lineChart.invalidate();

    }

    private static class UnitValueFormatter extends ValueFormatter {

        private final SnapshotData.Unit unit;
        private final List<Snapshot> mSnapshots;

        public UnitValueFormatter(SnapshotData.Unit unit, List<Snapshot> mSnapshots) {
            this.unit = unit;
            this.mSnapshots = mSnapshots;
        }

        private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA);

        @Override
        public String getFormattedValue(float value) {
            String valueString = value + "";
            try {
                Calendar c = Calendar.getInstance();
                String dateString = mSnapshots.get((int) value).getDate();
                if (unit == SnapshotData.Unit.month) {
                    dateString += "-01";
                }
                c.setTime(sdf.parse(dateString));
//                int y = c.get(Calendar.YEAR);
                int m = c.get(Calendar.MONTH) + 1;
                int d = c.get(Calendar.DAY_OF_MONTH);
                switch (unit) {
                    case day:
                        valueString = String.format("%s日", d);
                        break;
                    case week:
                        valueString = String.format("%s-%s", m, d);
                        break;
                    case month:
                        valueString = String.format("%s月", m);
                        break;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return valueString;
        }
    }

    private static class UnitMarkerView extends MyMarkerView {

        private final SnapshotData.Unit unit;
        private final List<Snapshot> mSnapshots;

        public UnitMarkerView(Context context, SnapshotData.Unit unit, List<Snapshot> mSnapshots) {
            super(context);
            this.unit = unit;
            this.mSnapshots = mSnapshots;
        }

        @Override
        protected void onItemSelected(int xPos, TextView msg) {

        }
    }

}